<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总共{{ total }}条</span>
        </template>
        <template #right>
          <el-button round size="small" type="warning" @click="$router.push('/employees/import')">导入 Excel</el-button>
          <el-button v-allow="'export_employee'" round size="small" type="danger" @click="hExpot">导出 Excel</el-button>
          <el-button round size="small" type="primary" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>
      <el-card style="margin-top: 20px">
        <el-table :data="employees">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template v-slot="{ row }">
              <!-- <img class="avatar" :src="row.staffPhoto" alt=""> -->
              <image-holder :src="row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式">
            <template v-slot="{row}">
              {{ formatEmployment(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column sortable label="入职时间">
            <template v-slot="{ row }">
              {{ formatDate(row.timeOfEntry) }}
            </template>
          </el-table-column>

          <el-table-column label="操作">
            <template v-slot="{row}">
              <el-button type="text" @click="$router.push('/employees/detail/' + row.id)">查看</el-button>
              <el-button type="text" @click="hassion(row.id)">分配角色</el-button>
              <el-button type="text" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style="height: 60px; margin-top: 10px">
          <el-pagination
            :current-page="q.page"
            :page-sizes="[10, 15, 20, 30]"
            :page-size="q.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="hSizeChange"
            @current-change="hCurrentChange"
          />
        </div>
      </el-card>
    </div>
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      title="新增员工"
      width="45%"
      :visible.sync="showDialog"
      @closed="hclosed"
    >
      <emp-dialog ref="empDialog" @success="hSuccess" @close="showDialog = false" />
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      title="新增员工"
      width="45%"
      :visible.sync="showDialogRole"
      @closed="$refs.assignRole.resetIds()"
    >
      <assign-role :id="curId" ref="assignRole" @close="showDialogRole=false" />
    </el-dialog>
  </div>
</template>
<script>
import { delEmployee, gEmploy } from '@/api/employ'
import empConstant from '@/constant/employees'
import AssignRole from './assignRole'
import empDialog from './empDialog.vue'
import dayjs from 'dayjs'

// 准备一个映射对象, 最终目标是: { 1: '正式', 2: '非正式' }
const hireTypeMap = {}
// 可选作业: 把 forEach 变成 reduce
// 执行循环后达成目标: { 1: '正式', 2: '非正式' }
empConstant.hireType.forEach(item => {
  hireTypeMap[item.id] = item.value
})
export default {
  components: {
    empDialog,
    AssignRole
  },
  data() {
    return {
      employees: [],
      total: 0,
      q: {
        page: 1,
        size: 10
      },
      showDialog: false,
      showDialogRole: false,
      curId: ''
    }
  },
  created() {
    this.loademopy()
  },
  methods: {
    async loademopy() {
      const res = await gEmploy(this.q)
      this.total = res.data.total
      this.employees = res.data.rows
    },
    formatEmployment(code) {
      // const resul = empConstant.hireType.find(item => item.id === code)
      // if (resul) {
      //   return resul.value
      // } else {
      //   return '未知'
      // }
      return hireTypeMap[code]
    },
    hSizeChange(size) {
      this.q.size = size
      this.loademopy()
    },
    hCurrentChange(page) {
      this.q.page = page
      this.loademopy()
    },
    async hDel(id) {
      try {
        await this.$confirm('真的删除么', '提示', { type: 'warning' })
        const res = await delEmployee(id)
        this.$message.success(res.message)
        // 判断: 当前是否为最后一条数据, 并且当前页 > 1, 需要 -1
        if (this.employees.length === 1 && this.q.page > 1) {
          this.q.page--
        }
        this.loademopy()
      } catch (e) {
        if (e === 'cancel') return
        this.$message.error(e.message)
      }
    },
    hSuccess() {
      this.showDialog = false
      this.total++
      this.q.page = Math.ceil(this.total / this.q.size)
      this.loademopy()
    },
    formatDate(data) {
      return dayjs(data).format('YYYY-MM-DD')
    },
    hclosed() {
      this.$refs.empDialog.resetForm()
    },
    async  hExpot() {
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      const res = await gEmploy({ page: 1, size: this.total })
      const list = res.data.rows
      // const zhlist = list.map(enobj => {
      //   const zhobj = {}
      //   const enkeys = Object.keys(enobj)
      //   enkeys.forEach(enkey => {
      //     const zhkey = mapInfo[enkey]
      //     zhobj[zhkey] = enobj[enkey]
      //   })
      //   return zhobj
      // })
      // const first = zhlist[0]
      const first = list[0]
      if (!first) return
      // const header = Object.keys(first)
      const header = Object.keys(first).map(enKey => mapInfo[enKey])
      const data = list.map(item => {
        const code = item['formOfEmployment']
        item['formOfEmployment'] = hireTypeMap[code]
        return Object.values(item)
      })
      const excel = await import('@/vendor/Export2Excel')
      excel.export_json_to_excel({
        header,
        data,
        filename: '陈氏大公司员工',
        autoWidth: true,
        bookType: 'xlsx'
      })
    },
    async hassion(id) {
      this.showDialogRole = true
      this.curId = id
      await this.$nextTick()
      this.$refs.assignRole.loadRoleIds()
    }
  }
}
</script>
<style lang="scss" scoped>
.avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
}
.el-pagination {
  height: 60px;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
